package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import com.itheima.reggie.dto.CategoryDiagram;
import com.itheima.reggie.dto.DrilldownSeries;
import com.itheima.reggie.dto.SunBurstChild;
import com.itheima.reggie.dto.SunBurstParent;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author : xyiaao
 * @createDate : 2022/3/2 9:05
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @CacheEvict(value = "categoryCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("Category:{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page , int pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);

        //分页查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 分类删除
     * @param id
     * @return
     */
    @CacheEvict(value = "categoryCache", allEntries = true)
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("分类删除,id为:{}",id);
        //调用写的remove方法
        categoryService.remove(id);
        return R.success("删除分类成功");
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @CacheEvict(value = "categoryCache", allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }


    @Cacheable(value = "orderCache", key = "'dishSaleNum_' + #beginTime + '_' + #endTime", unless = "#result == null")
    @GetMapping("/dishSaleNum")
    public R<List<CategoryDiagram>> dishSaleNum(String beginTime, String endTime) {

        List<Category> categoryList;
        {
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Category::getId, Category::getName);
            // 查询菜品分类
            queryWrapper.eq(Category::getType, 1);
            categoryList = categoryService.list(queryWrapper);
        }

        List<CategoryDiagram> categoryDiagramList = categoryList.stream().map(category -> {
            // 根据分类id查询菜品
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Dish::getId, Dish::getName);
            queryWrapper.eq(Dish::getCategoryId, category.getId());
            List<Dish> dishList = dishService.list(queryWrapper);

            CategoryDiagram categoryDiagram = new CategoryDiagram();
            categoryDiagram.setY(0);
            // 查询该分类id下的所有菜品的月销量
            Object[] array = dishList.stream().map(dish -> {
                Integer num = dishService.countSaleNum(dish.getId(), beginTime, endTime);
                // 将月销量进行相加，得到该分类的月销量
                categoryDiagram.setY(categoryDiagram.getY() + num);
                // 将菜品名称和销量封装为一个数组
                return new Object[]{dish.getName(), num};
                // 获得一个二维数组
            }).toArray();
            // 设置分类名
            categoryDiagram.setName(category.getName());
            // 设置分类名
            categoryDiagram.setDrilldown(category.getName());

            DrilldownSeries drilldownSeries = new DrilldownSeries();
            // 设置分类名
            drilldownSeries.setId(category.getName());
            // 设置分类名
            drilldownSeries.setName(category.getName());
            // 设置分类下的菜品销量数据
            drilldownSeries.setData(array);

            categoryDiagram.setDrilldownSeries(drilldownSeries);
            return categoryDiagram;
        }).collect(Collectors.toList());
        return R.success(categoryDiagramList);
    }


    @Cacheable(value = "orderCache", key = "'dishSaleNumSun_' + #beginTime + '_' + #endTime", unless = "#result == null")
    @GetMapping("/dishSaleNumSun")
    public R<SunBurstParent[]> dishSaleNumSun(String beginTime, String endTime) {
        List<SunBurstParent> sunBurstList = new LinkedList<>();

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 查询菜品分类
        queryWrapper.eq(Category::getType, 1);
        List<Category> categoryList = categoryService.list(queryWrapper);
        String one = "1.";
        String two = "2.";
        int id = 1;
        String oneParent = "0.0";
        SunBurstParent root = new SunBurstParent();
        root.setId(oneParent);
        root.setName("菜品");
        root.setParent("");
        // 将跟数据添加到集合中
        sunBurstList.add(root);
        for (int i = 0; i < categoryList.size(); i++) {
            // 获取分类对象
            Category category = categoryList.get(i);

            // 创建数据对象
            SunBurstParent sunBurstOne = new SunBurstParent();
            // 创建二级数据的父id(即一级数据的id)
            String twoParent = one + (i + 1);
            sunBurstOne.setId(twoParent);
            sunBurstOne.setParent(oneParent);
            sunBurstOne.setName(category.getName());
            // 将一级数据（分类）添加到集合中
            sunBurstList.add(sunBurstOne);

            // 根据分类id查询菜品
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getCategoryId, category.getId());
            List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);
            for (Dish dish : dishList) {
                SunBurstChild sunBurstTwo = new SunBurstChild();
                sunBurstTwo.setId(two + id++);
                sunBurstTwo.setParent(twoParent);
                sunBurstTwo.setName(dish.getName());
                Integer num = dishService.countSaleNum(dish.getId(), beginTime, endTime);
                sunBurstTwo.setValue(num);
                // 将二级数据（菜品）添加到集合中
                sunBurstList.add(sunBurstTwo);
            }
        }
        SunBurstParent[] sunBurstArr = sunBurstList.toArray(new SunBurstParent[sunBurstList.size()]);
        return R.success(sunBurstArr);
    }


    /**
     * 根据条件(类型)查询分类数据
     *
     * @param category
     * @return
     */
    @Cacheable(value = "categoryCache", key = "'category_' + #category.type", unless = "#result == null")
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        // 条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        // 添加条件
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        // 添加排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
